package org.raymond.iworks.core.security;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.raymond.iworks.core.constants.SecurityComponets;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;

import java.time.Instant;

@NoArgsConstructor
@Data
public class UsernameCertification implements Certification, Principal {
    private static Argon2PasswordEncoder encoder = SecurityComponets.ARGON2_PASSWORD_ENCODER;
    // token
    private String certification;
    private long expire;
    private long expireAt;

    private long id;
    private String username;
    private String password;

    public UsernameCertification(String u, String p){
        username = u;
        password = p;
    }

    @Override
    public void setExpire(long expire){
        this.expire = expire;
        long timestamp = Instant.now().getEpochSecond();
        this.expireAt = timestamp+expire;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        UsernameCertification that = (UsernameCertification) o;
        return username.equals(that.username)
                && encoder.matches(that.password, password);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(username).append(password).toHashCode();
    }

    @Override
    public boolean authenticate(Certification anOther) {
        return equals(anOther);
    }
}
